<template>
	<view class="main animated fadeIn faster">
		<TitleBarVue :title="title"/>
		<view class="position-fixed z-index-10" style="padding-top: 200rpx; background: #fff; width: 100%;">
			<view class="srch d-flex d-flex-middle position-absolute" style="width: 700rpx; left: 25rpx;">
				<text class="iconfont icon-sousuo colorblue position-absolute" style="left: 20rpx;"></text>
				<input type="text" @input="SearchGames" v-model="searchVal" class="srchInput" placeholder="请输入关键字"/>
			</view>
			<view class="d-flex d-flex-middle d-flex-between ml-3" style="margin-top: 85rpx;">
				<view class="d-flex d-flex-middle">
					<view class="font32" style="color: #1f1f1f;">常玩游戏</view>
					<view class="ml-2" style="color: #acacb0;" v-if="testEdits">{{oftenUseGameList.length}} / 5</view>
				</view>
				<view class="mr-3" v-if="!testEdits" @click="editGame">管理</view>
				<view class="mr-3" style="color: #40b2db;" v-if="testEdits" @click="editGame">完成</view>
			</view>
			<view class="d-flex d-flex-middle d-flex-wrap ml-3 mb-3">
				<view v-if="oftenUseGameList.length!==0" class="position-relative mr-3 mt-3" v-for="i in oftenUseGameList" :key="i.id">
					<view class="rounded10 gameLabel w-100" @click="TabChooseGame(i)">{{i}}</view>
					<view @click="remoteOftenGame(i,'default')" v-show="testEdits" class="position-absolute rounded d-flex-btn" style="width: 30rpx; height: 30rpx; background: #c5cad0; top: -10rpx; right: -10rpx;">
						<image src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/close-fff.png" style="width: 15rpx; height: 15rpx;"></image>
					</view>
				</view>
				<view v-else class="w-100 text-center mt-2" style="height: 90rpx; line-height: 90rpx; color: #c9c9c9;">您还没添加常玩游戏哦~</view>
			</view>
			<view style="background: #f5f4f9; width: 100%; height: 10rpx;"></view>
			<view class="font32 pl-3 py-1 mt-1" id="Boundary" style="color: #1f1f1f;">选择游戏</view>
		</view>
		<view class="d-flex d-flex-wrap d-flex-between px-2 mb-3" :style="{'paddingTop':GameListPaddingTop + 'px'}">
			<view class="gameItem d-flex-column d-flex-middle mt-2" v-for="(i, index) in GameList" :key="i.id" @click="chooseGames(i)">
				<view class="position-relative" style="width: 100%;">
					<view @click.stop="testEdits ? addOftensGame(i, index, 'default') : chooseGames(i)">
						<image :src="i.icon" mode="widthFix" style="width: 100%;"></image>
					</view>
					<view v-if="i.edit">
						<view v-if="!i.checked" @click.stop="addOftensGame(i,index,'default')" class="position-absolute rounded d-flex-btn" style="width: 30rpx; height: 30rpx; background: #c5cad0; top: -18rpx; right: -18rpx;">
							<image src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/add.png" style="width: 18rpx; height: 18rpx;"></image>
						</view>
						<view v-if="i.checked" @click.stop="remoteOftenGame(i.name,'default')" class="position-absolute rounded d-flex-btn" style="width: 30rpx; height: 30rpx; background: #18c3ff; top: -18rpx; right: -18rpx;">
							<image src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/checked.png" style="width: 18rpx; height: 18rpx;"></image>
						</view>
					</view>
				</view>
				<view class="gameText">{{i.name}}</view>
			</view>
		</view>
	</view>
</template>

<script>
	import TitleBarVue from '../../components/TitleBar.vue';
	import { DictionaryApi } from '../../http/dictionary';
	import { userApi } from '../../http/userApi';
	import { DaziApi } from '../../http/Dazi';
	import store from '@/store/index.js';
	import {dateUtils} from '@/util/util.js';
	export default {
		data() {
			return {
				title: '全部游戏',
				max: false,
				SearchMax: false,
				GameListPaddingTop: 0,
				testEdits: false,
				searchVal: "",
				type: null,
				GameListParams: {
					pageIndex: 1,
					pageSize: 24
				},
				GameList: [],
				addFirst: '',
				oftenUseGameList: [],
				oftenUseGameId:[],
				selectedCity:''
			};
		},
		components: {TitleBarVue},
		onLoad() {
			this.selectedCity=this.$store.state.user.locatedCity;//记录位置信息
		},
		methods: {
			setGameListPaddingTop(){
				this.$nextTick(() => {
					let element = "#Boundary";
					let query = uni.createSelectorQuery().in(this);
					query.select(element).boundingClientRect();
					query.exec((res) => {
						this.GameListPaddingTop = res[0].top + res[0].height
					});
				})
			},
			async QueryGameList(isItCached) {
				const cacheKey = 'api_game_cache';
				  // 1. 先尝试读取缓存
				  const cachedData = await dateUtils.getCacheWithExpire(cacheKey);
				  
				  if (cachedData && isItCached) {
				    console.log('使用缓存数据',cachedData);
					this.GameList = cachedData
				  }
				  
				  // 2. 无缓存或过期则请求 API
				  try {
					let res = await DictionaryApi.GameList(this.GameListParams);
					if(res.records.length < res.size) {
						this.max = true;
					}
					res.records.forEach(item => {
						item.checked = this.oftenUseGameList.includes(item.name);
						item.edit = this.testEdits;
					});
					this.GameList = this.GameList.concat(res.records);
				    // 存储新数据（缓存 1 天）
				    dateUtils.setCacheWithExpire(cacheKey, this.GameList, 1);
				  } catch (error) {
				    console.error('API请求失败:', error);
				    // throw error;
				  }
			
			},
			async SearchGames() {
				let Params = {
					pageIndex: 1,
					pageSize: 24,
					name: this.searchVal
				}
				let res = await DictionaryApi.GameList(Params)
				res.records.forEach(item => {
					item.checked = false
				})
				this.GameList = res.records
			},
			async setUserInfo(){
				try{
					const usr = await userApi.getUserInfo()
				
					store.commit('setLogin',usr);
					store.commit("setPosition",this.selectedCity);
				}catch(e){
					console.log('login-info',e)
				}
			},
			async addGames(type) {
			    let favorGameLabel;
			
			    if (type == 2) {
			        // 如果 type 为 2，调用 this.only 方法处理 this.oftenUseGameId
			        favorGameLabel = this.only(this.oftenUseGameId);
			    } else {
			        // 如果 type 不为 2，调用 this.addIdToFirst 方法
			        favorGameLabel = this.addIdToFirst();
			    }
				let prarm={
					favorGameLabel:favorGameLabel
				}
			    // 调用 userApi.editUserInfo 方法更新用户信息
			    try {
			        let res = await userApi.editUserInfo(prarm);
			        console.log('更新用户信息成功:',prarm );
			    } catch (error) {
			        console.error('更新用户信息失败:', error);
			    }
			},
			only(ids) {//传多个值
			    const str = this.$store.state.user.favorGameLabel;
			    // 将字符串拆分成数组
			    let idArray = str.split(",").filter(id => id !== ''); // 过滤掉空字符串
			
			    // 创建一个 Set 来存储数组中的 id，方便快速查找和去重
			    const idSet = new Set(ids);
			
			    // 将字符串中的 id 也添加到 Set 中，自动去重
			    idArray.forEach(id => idSet.add(id));
			
			    // 将 Set 转换回数组
			    const uniqueIdArray = Array.from(idSet);
			
			    // 确保数组长度不超过5
			    const finalIdArray = uniqueIdArray.slice(0, 5);
			
			    // 将数组重新组合成字符串
			    const updatedStr = finalIdArray.join(",");
				this.setUserInfo();
			    return updatedStr;
			},
			addIdToFirst() {
			    const id = this.addFirst;
			    const str = this.$store.state.user.favorGameLabel;
			    // 将字符串拆分成数组
			    let idArray = str.split(",").filter(id => id !== ''); // 过滤掉空字符串
			
			    // 检查数组中是否已经包含该 id
			    const index = idArray.indexOf(id);
			    if (index !== -1) {
			        // 如果包含，则将该 id 移动到数组的最前面
			        idArray.splice(index, 1); // 从原位置删除
			    }
			    // 无论是否包含，都将该 id 添加到数组的最前面
			    idArray.unshift(id);
			
			    // 确保数组长度不超过5
			    const finalIdArray = idArray.slice(0, 5);
			
			    // 将数组重新组合成字符串
			    const updatedStr = finalIdArray.join(",");
				this.setUserInfo();
			   
			    return updatedStr;
			},
			
			editGame() {
				if (this.testEdits) {
					this.testEdits = false;
					this.GameList.forEach((game) => {
						game.edit = false;
					});
					// console.log(this.oftenUseGameList);
					// console.log(this.oftenUseGameId);
					uni.setStorageSync('oftenUseGameList', this.oftenUseGameList);
					uni.setStorageSync('oftenUseGameId', this.oftenUseGameId);
					this.addGames(2);
				} else {
					this.testEdits = true;
					this.GameList.forEach((game) => {
						game.edit = true;
						game.checked = this.oftenUseGameList.includes(game.name);
					});
				}
			},
			// 标签选择游戏
			TabChooseGame(i) {
				this.GameList.forEach((game)=>{
					if(game.name === i) {
						this.chooseGames(game)
					}
				})
			},
			async chooseGames(i) {
				if (!this.testEdits) {
					uni.setStorageSync('game', i);
					
					if (this.type == '1') {
						this.addFirst=i.id;
						this.addGames(1);
						uni.switchTab({
							url: '/pages/index/index'
						});
					} else if (this.type == '2') {
						uni.switchTab({
							url: '/pages/star/star',
							success: function (e) {
								var page = getCurrentPages()[0];
								if (page) {
									page.$vm.addAvatar();
								}
							}
						});
					} else {
						console.log(i);
						let name = i.name;
						let id = i.id;
						let icon = i.icon;
						let param = {
							pageIndex: 1,
							pageSize: 20,
							uid: this.$store.state.user.uid,
							status: 1
						}
						let res = await DaziApi.queryCard(param);
						let records = res.records;
						if (records.length == 0) {
							uni.navigateTo({
								url: `/pagesMain/edite-card/edite-card?id=${id}&name=${encodeURIComponent(name)}&icon=${encodeURIComponent(icon)}`
							})
						} else {
							let foundItem = null;
							const hasGame = records.some(i => {
								if (i.gameId === id) {
									foundItem = i; // 保存找到的元素
									return true; // 找到符合条件的元素，返回true
								}
								return false;
							});
							if (hasGame) {
								console.log('有这个搭子卡');
								uni.navigateTo({
									url: `/pagesApp/edit/edit?id=${foundItem.id}&gameId=${foundItem.gameId}`
								});
							} else {
								console.log('没有这个搭子卡');
								uni.navigateTo({
									url: `/pagesMain/edite-card/edite-card?id=${id}&name=${encodeURIComponent(name)}&icon=${encodeURIComponent(icon)}`
								});
							}
						}
					}
				}
			},
			addOftensGame(i, index, type) {
				if (this.oftenUseGameList.includes(i.name)) {
					this.remoteOftenGame(i.name);
					
					this.GameList[index].checked = false;
					uni.showToast({
						icon: "none",
						title: '已取消选择该游戏',
						duration: 1500
					});
					return;
				}
				
				if (this.oftenUseGameList.length < 5) {
					this.oftenUseGameList.push(i.name);
					this.oftenUseGameId.push(i.id);
					this.GameList[index].checked = true;
					this.setGameListPaddingTop();
				} else {
					uni.showToast({
						icon: "none",
						title: '最多勾选5项游戏哦',
						duration: 1500
					});
				}
			},
			remoteOftenGame(name) {
				const index = this.oftenUseGameList.findIndex(i => i === name);
				if (index !== -1) {
					this.oftenUseGameList.splice(index, 1);
					this.oftenUseGameId.splice(index,1);
					const gameIndex = this.GameList.findIndex(game => game.name === name);
					if (gameIndex !== -1) {
						this.GameList[gameIndex].checked = false;
					}
					this.setGameListPaddingTop();
				}
			}
		},
		onReachBottom() {
			if(!this.max) {
				this.GameListParams.pageIndex++;
				this.QueryGameList(true).then(() => {
					if (this.testEdits) {
						this.GameList.forEach((game) => {
							game.edit = true;
							game.checked = this.oftenUseGameList.includes(game.name);
						});
					}
				});
			}
		},
		onLoad(opt) {
			this.type = opt.type
			this.setGameListPaddingTop()
			this.QueryGameList(true)
			this.oftenUseGameList = uni.getStorageSync('oftenUseGameList') || [];
			this.oftenUseGameId=uni.getStorageSync('oftenUseGameId')|| [];
			this.setUserInfo();
		}
	};
	
</script>

<style scoped lang="scss">
.main {
	background: #fff;
	overflow: hidden;
	.content {
		width: 100%;
		background-color: #fff !important;
	}
}
.srchInput {
	background: #f4f5fa;
	border-radius: 40rpx;
	width: 100%;
	height: 60rpx;
	padding-left: 58rpx;
}
.gameLabel {
	background: #f4f5fa;
	width: 175rpx;
	text-align: center;
	line-height: 80rpx;
	height: 80rpx;
	overflow: hidden;
	text-overflow: ellipsis;
	display: -webkit-box;
	overflow:hidden;
	-webkit-line-clamp: 1; //多行在这里修改数字即可
	-webkit-box-orient: vertical;
}
.gameItem {
	width: calc(25% - 12px);
	margin-right: 12px;
	.gameText {
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		overflow:hidden;
		-webkit-line-clamp: 1; //多行在这里修改数字即可
		-webkit-box-orient: vertical;
		padding: 0 10rpx;
	}
}
.gameItem:nth-child(4n) {
	margin-right: 0;
}
.gameItem:last-child:nth-child(4n + 2) {
	margin-right: calc((100% - 25%) / 3 * 2);
}
.gameItem:last-child:nth-child(4n + 3) {
	margin-right: calc((100% - 25%) / 3 * 1);
}
</style>
